<!--
 * @Author: your name
 * @Date: 2021-04-01 11:40:19
 * @LastEditTime: 2021-04-27 09:06:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \active-front\src\components\Notfound\index.vue
-->
<template>
  <div>
    <el-row type="flex">
      <el-col :span="6">
        <div style="font-size:18px">请选择出行方式:</div>
        <el-radio-group
          v-model="radio"
          style="margin: 10px 0"
          size="mini"
          @change="onChange"
        >
          <el-radio-button label="公交"></el-radio-button>
          <el-radio-button label="步行"></el-radio-button>
          <el-radio-button label="骑行"></el-radio-button>
          <el-radio-button label="驾车"></el-radio-button>
          <el-radio-button label="货车" disabled></el-radio-button>
        </el-radio-group>
        <div style="font-size:18px">请选择前往的活动地点:</div>
        <el-menu default-active="2" class="el-menu-vertical-demo" @select="go">
          <el-submenu
            v-for="(item, index) in options"
            :index="index.toString()"
            style="width:80%"
            :key="item.value"
          >
            <template slot="title">
              <i class="el-icon-location"></i>
              <span>{{ item.label }}</span>
            </template>
            <el-menu-item-group>
              <template slot="title">{{ item.label }}</template>
              <el-menu-item
                :index="data.value.join(' ')"
                v-for="data in item.children"
                :key="data.value.join(' ')"
                >{{ data.label }}</el-menu-item
              >
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-col>
      <el-col :span="18" style="position: relative;">
        <div class="toolbar">
          <span>{{ loaded }}</span>
        </div>
        <div id="panel" v-if="center"></div>
        <el-amap
          :amap-manager="amapManager"
          vid="amap"
          :plugin="plugin"
          class="amap-demo"
          :center="center"
          :zoom="zoom"
          id="container"
          style="width:100%;height:75vh"
          :events="events"
          ref="map"
        >
          <el-amap-marker
            v-for="marker in markers"
            :position="marker.position"
            :key="marker.id"
            :events="marker.events"
            :icon="marker.icon"
          ></el-amap-marker>
          <el-amap-info-window
            v-if="window"
            :position="window.position"
            :visible="window.visible"
            :content="window.content"
            :offset="window.offset"
          ></el-amap-info-window>
        </el-amap>
      </el-col>
      <!-- <el-col :span="3"></el-col> -->
    </el-row>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
import { AMapManager } from "vue-amap";
let amapManager = new AMapManager();
export default {
  data() {
    let that = this;
    let initDel = false;
    return {
      radio: "公交",
      value: "", //定位位置
      driving: "", //上一次规划路线
      planRoute: "Transfer", //默认为公交
      planRouteArr: [
        { name: "公交", value: "Transfer" },
        { name: "步行", value: "Walking" },
        { name: "骑行", value: "Riding" },
        { name: "驾车", value: "Driving" },
        { name: "货车", value: "TruckDriving" }
      ],
      /**
       * 公交路线规划（AMap.Transfer）
       * 步行路线规划（AMap.Walking）
       * 骑行路线规划（AMap.Riding）
       * 货车路线规划（AMap.TruckDriving）
       * 驾车路线规划 Driving
       */
      amapManager,
      options: [
        {
          value: "成龙校区",
          label: "成龙校区",
          children: [
            {
              value: [104.198146, 30.564495],
              label: "第一教学楼"
            },
            {
              value: [104.201418, 30.562703],
              label: "第一实验楼"
            },
            {
              value: [104.201032, 30.56493],
              label: "学生活动中心"
            },
            {
              value: [104.198618, 30.565327],
              label: "办公楼"
            },
            {
              value: [104.201429, 30.565918],
              label: "图书馆"
            },
            {
              value: [104.196644, 30.56407],
              label: "第二实验大楼"
            },
            {
              value: [104.197642, 30.563609],
              label: "第三实验大楼"
            },
            {
              value: [104.200453, 30.564422],
              label: "龙湖剧场"
            },
            {
              value: [104.20306, 30.564431],
              label: "第一运动场"
            },
            {
              value: [104.198833, 30.567507],
              label: "第二运动场"
            },
            {
              value: [104.203854, 30.561973],
              label: "东苑"
            },
            {
              value: [104.198119, 30.56559],
              label: "西苑"
            }
          ]
        },
        {
          value: "狮山校区",
          label: "狮山校区",
          children: [
            {
              value: [104.121569, 30.609037],
              label: "第二教学楼"
            },
            {
              value: [104.121805, 30.610515],
              label: "第三教学楼"
            },
            {
              value: [104.121274, 30.610044],
              label: "第四教学楼"
            },
            {
              value: [104.121263, 30.608663],
              label: "第六教学楼"
            },
            {
              value: [104.122599, 30.610815],
              label: "第七教学楼"
            },
            {
              value: [104.123672, 30.613151],
              label: "学生活动中心"
            },
            {
              value: [104.124686, 30.61244],
              label: "体育场"
            },
            {
              value: [104.1238, 30.610866],
              label: "生态广场"
            },
            {
              value: [104.125599, 30.611387],
              label: "聚贤楼"
            }
          ]
        }
      ],
      center: [121.126757, 31.140653], //地图中心
      mapStyle: "amap://styles/blue", //修改地图的背景颜色
      markers: [], //点坐标
      windows: [], //点击坐标后的弹窗
      window: "",
      adress: "",
      loaded: "定位中,请稍候!",
      zoom: 1, //默认缩放比例 1最大 不过这里并没有用
      events: {
        //地图点击事件
        click: e => {
          let { lng, lat } = e.lnglat;
          that.lng = lng;
          that.lat = lat;
          if (initDel) {
            that.markers.pop();
          } else {
            initDel = true;
          }
          that.markers.push({
            position: [lng, lat],
            // icon: location, //不设置默认蓝色水滴
            events: {
              click() {
                that.$nextTick();
                // that.windows.forEach(window => {
                //   window.visible = false; //关闭窗体
                // });
                // that.window = that.windows[markers.length];
                // that.$nextTick(() => {
                //   that.window.visible = true; //点击点坐标，出现信息窗体
                // });
              }
            }
          });

          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                that.loaded =
                  "当前定位为：" + result.regeocode.formattedAddress;
                that.center = [that.lng, that.lat];
                that.$nextTick();
              }
            }
          });
        },
        //地图平移事件
        moveend: e => {
          let [lng, lat] = that.$refs.map.$$getCenter(); //获取平移后的经纬度
          that.lng = lng;
          that.lat = lat;
          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                that.loaded =
                  "当前定位为：" + result.regeocode.formattedAddress;
                that.position = result.regeocode.formattedAddress;
                that.$nextTick();
              }
            }
          });
        }
      },
      plugin: [
        {
          pName: "Geolocation",
          zoomToAccuracy: true,
          timeout: 20,
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  // // alert(result.formattedAddress);
                  that.zoom = 13; // 如果key是企业的，还可以直接result.addressComponent获取省市，周边等信息
                  that.adress = result.formattedAddress;
                  that.loaded = "当前定位为:" + that.adress;
                  that.center = [result.position.lng, result.position.lat];
                  that.value = [result.position.lng, result.position.lat];
                  that.$nextTick();
                } else {
                  that.loaded = "获取定位失败,请重试!";
                }
              });
            }
          }
        },
        {
          //地图工具条
          pName: "ToolBar",
          init(o) {}
        }
        // {
        //   //左下角缩略图插件 比例尺
        //   pName: "Scale",
        //   init(o) {}
        // }
      ]
    };
  },

  methods: {
    onChange(val) {
      let that = this;
      this.planRouteArr.map(item => {
        if (item.name === val) {
          that.planRoute = item.value;
        }
      });
      if (that.driving) that.setLine();
    },
    // 绘制路径
    setLine() {
      let that = this;
      let map = that.amapManager.getMap();
      //构造路线导航类
      AMap.service("AMap." + that.planRoute, function() {
        //回调函数

        // 单独移除点标记
        // map.remove([that.lastValue, that.lastCenter]);
        // 同时移除点标记和矢量圆形
        // map.remove([marker, circle]);
        // // 使用clearMap方法删除所有覆盖物
        // map.clearMap();
        // that.point();
        if (that.driving) that.driving.clear();
        that.driving = new AMap[that.planRoute]({
          map: map,
          panel: "panel",
          city: "成都"
          // policy: AMap.DrivingPolicy.REAL_TRAFFIC
          /**
           * AMap.DrivingPolicy.LEAST_TIME 	最快捷模式
           * AMap.DrivingPolicy.LEAST_FEE  	最经济模式
           * AMap.DrivingPolicy.LEAST_DISTANCE 最短距离
           * AMap.DrivingPolicy.REAL_TRAFFIC 考虑实时路况
           */
        });
        // 根据起终点经纬度规划驾车导航路线
        that.driving.search(that.value, that.center, function(status, result) {
          // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === "complete") {
            that.$message({
              message: "绘制驾车路线完成",
              type: "success",
              center: true
            });
          } else {
            that.$message({
              message: "绘制驾车路线失败" + result,
              type: "error",
              center: true
            });
          }
        });
      });
    },
    //地图平移到指定经纬度 并重新规划路线
    go(key, keyPath) {
      console.log(key, keyPath);
      key = key.split(" ");
      this.center = key;
      this.setLine();
      this.$nextTick();
    },
    point() {
      let markers = [];
      let windows = [];
      let that = this;
      let pointMarker = [];
      this.options.map(item => {
        for (let obj in item.children) {
          pointMarker.push({
            lng: item.children[obj].value[0],
            lat: item.children[obj].value[1],
            stationName: item.label, //学院名称
            buildTime: "2011-12-08", //建站时间
            stationAddress: item.children[obj].label, //活动站址
            temperature: "25.5℃", //温度
            rainfall: "5mm", //雨量
            windDirection: "西北", //风向
            windSpend: "2.05m/s", //风速
            waterLevel: "2.65m", //水位
            waterVelocity: "1.2m/s", //流速
            waterTraffic: "2.8m³/s" //流量
          });
        }
      });
      // let pointMarker = [
      //   {
      //     lng: 104.201044,
      //     lat: 30.561861,
      //     stationName: "四川示范大学成龙校区",
      //     buildTime: "2011-12-08", //建站时间
      //     stationAddress: "音乐学院", //站址
      //     temperature: "25.5℃", //温度
      //     rainfall: "5mm", //雨量
      //     windDirection: "西北", //风向
      //     windSpend: "2.05m/s", //风速
      //     waterLevel: "2.65m", //水位
      //     waterVelocity: "1.2m/s", //流速
      //     waterTraffic: "2.8m³/s" //流量
      //   },
      //   {
      //     lng: 121.037746,
      //     lat: 31.105422,
      //     stationName: "青浦水文站2",
      //     buildTime: "2011-12-08", //建站时间
      //     stationAddress: "上海市牛头山路东100m", //站址
      //     temperature: "25.5℃", //温度
      //     rainfall: "5mm", //雨量
      //     windDirection: "西北", //风向
      //     windSpend: "2.05m/s", //风速
      //     waterLevel: "2.65m", //水位
      //     waterVelocity: "1.2m/s", //流速
      //     waterTraffic: "2.8m³/s" //流量
      //   }
      // ];
      pointMarker.forEach((item, index) => {
        markers.push({
          position: [item.lng, item.lat],
          // icon: location, //不设置默认蓝色水滴
          events: {
            click() {
              that.windows.forEach(window => {
                window.visible = false; //关闭窗体
              });
              that.window = that.windows[index];
              that.$nextTick(() => {
                that.window.visible = true; //点击点坐标，出现信息窗体
              });
            }
          }
        });
        windows.push({
          position: [item.lng, item.lat],
          content:
            "" +
            "<div>" +
            "学院名称：" +
            item.stationName +
            "</div>" +
            "<div>" +
            "活动时间：" +
            item.buildTime +
            "</div>" +
            "<div>" +
            "地 址：" +
            item.stationAddress +
            "</div>" +
            "<div>" +
            "温度：" +
            "<span style='color: #66A0FF'>" +
            item.temperature +
            "</span>" +
            "</div>" +
            "<div>" +
            "雨量：" +
            "<span style='color: #66A0FF'>" +
            item.rainfall +
            "</span>" +
            "</div>" +
            "<div>" +
            "风向：" +
            "<span style='color: #66A0FF'>" +
            item.windDirection +
            "</span>" +
            "</div>" +
            "<div>" +
            "风速：" +
            "<span style='color: #66A0FF'>" +
            item.windSpend +
            "</span>" +
            "</div>" +
            "<div>" +
            "水位：" +
            "<span style='color: #66A0FF'>" +
            item.waterLevel +
            "</span>" +
            "</div>" +
            "<div>" +
            "流速：" +
            "<span style='color: #66A0FF'>" +
            item.waterVelocity +
            "</span>" +
            "</div>" +
            "<div>" +
            "流量：" +
            "<span style='color: #66A0FF'>" +
            item.waterTraffic +
            "</span>" +
            "</div>",
          offset: [5, -15], //窗体偏移
          visible: false //初始是否显示
        });
      });
      //添加点标注
      this.markers = markers;
      //生成弹窗
      this.windows = windows;
    },
    ...mapMutations(["activeIndexUpdate"])
  },
  mounted() {
    this.activeIndexUpdate("/info/map");
    this.point();
  }
};
</script>

<style scoped>
#panel {
  position: absolute;
  background-color: white;
  /* max-height: 100%; */
  z-index: 150;
  overflow-y: auto;
  top: -10px;
  right: 10px;
  width: 280px;
}
</style>
